package com.shou.zhnfyxt.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.shou.zhnfyxt.entity.Error;
import com.shou.zhnfyxt.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class AuthenticationEntryPointImpl  implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.info(String.valueOf(authException));
        if(authException instanceof InternalAuthenticationServiceException){
            response.getWriter().print(JSONObject.toJSONString(R.error(Error.USERNAMENOTEXIST)));
        }
        if(authException instanceof BadCredentialsException){
            response.getWriter().print(JSONObject.toJSONString(R.error(Error.USERNAMEISNOTMATCHPASSWORD)));
        }
        if (authException instanceof InsufficientAuthenticationException){
            response.getWriter().print(JSONObject.toJSONString(R.error(Error.HASNOTOKEN)));
        }
    }
}
